# -* - coding: UTF-8 -* -
#import sys
#reload(sys)
#sys.setdefaultencoding('utf8')
import sys,importlib
import threading,string
import socket
from time import sleep
from task import *
from command.task import *
from command.thread import *
import logging

#从外部队列读取消息放入内部对列
class CommandCenter():  
	def __init__(self,service_center,config,server_list=['127.0.0.1']):
		self.service_center = service_center
		self.config = config
		self.queue = Thread.Queue()
		self.threads = []
		self.server_list = server_list
		self.create_threads()
		self.udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)


	#创建
	def create_threads(self):
		thread_count = self.config.get_int('coop','command_thread_count',1)
		for i in range(thread_count):#10线程执行
			t = CommandThread(self.queue)  
			self.threads.append(t)
	
	def start(self):
		for t in self.threads:
			t.start_thread()
			
	def stop(self):
		self.udp.close()
		for t in self.threads:
			t.stop_thread()
			
	def terminate(self):
		for t in self.threads:
			t.terminate()				
	
	def sendAll(self,data):
		for s in self.server_list:
			address = (s,9981)
			self.udp.sendto(data.encode('utf8'), address)
	
		
	#防火墙命令
	def execute(self,task):
		commander = self.service_center.get(task.type)
		if commander:
			task=CommandTask(commander,task.command,task.data)
			self.queue.put(task)
		
